//
//  DAnalysisDateCustomController.swift
//  Drop
//
//  Created by hushaohua on 2018/2/12.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit

class DAnalysisDateCustomController{
    
    var intervalType:DAnalysisDatePreference.IntervalTypes = .Day;
    var isEditing:Bool = false;
    
    var beginButton:UIButton?;
    var endButton:UIButton?;
    func configCustomDateCell(_ cell:UITableViewCell) -> Void {
        self.beginButton = self.customDateBeginButton(cell.frame);
        cell.contentView.addSubview(self.beginButton!);
        self.endButton = self.customDateEndButton(cell.frame);
        cell.contentView.addSubview(self.endButton!);
        if (self.beginIsSelected){
            self.beginButton!.isSelected = true;
            self.endButton!.isSelected = false;
        }else{
            self.beginButton!.isSelected = false;
            self.endButton!.isSelected = true;
        }
        self.beginButton!.setTitle("从\(self.beginDate.defaultDateString())", for: .normal);
        self.endButton!.setTitle("至\(self.endDate.defaultDateString())", for: .normal);
        cell.contentView.addSubview(self.customDateDoneButton(cell.frame));
    }
    
    func configDatePickerCell(_ cell:UITableViewCell) -> Void{
        self.datePicker = self.datePicker(cell.frame);
        cell.addSubview(self.datePicker!);
    }
    
    var datePicker:UIDatePicker?;
    func datePicker(_ superFrame:CGRect) -> UIDatePicker {
        let picker:UIDatePicker = UIDatePicker(frame: CGRect(x:0,y:0,width:superFrame.width,height:superFrame.size.height));
        picker.autoresizingMask = [.flexibleWidth, .flexibleHeight];
        picker.backgroundColor = UIColor.white;
        picker.datePickerMode = .date;
        picker.date = Date();
        picker.minimumDate = DDateManager.sharedManager().initialDate();
        picker.maximumDate = Date();
        picker.addTarget(self, action: #selector(datePickerChanged(_:)), for: .valueChanged);
        return picker;
    };
    
    @objc func datePickerChanged(_ sender:UIDatePicker) -> Void{
        let dateFormatter = DateFormatter();
        var calendar:Calendar = Calendar.current;
        calendar.firstWeekday = 2;
        let date = sender.date;
        let today = Date();
        let dateComp = calendar.dateComponents([.year, .month, .day, .yearForWeekOfYear, .weekOfYear, .weekday], from: date);
        let todayComp = calendar.dateComponents([.year, .month, .day, .yearForWeekOfYear, .weekOfYear, .weekday], from: today);
        var adjustDate:Date = date;
        if (self.beginButton != nil && self.beginButton!.isSelected){
            switch self.intervalType {
            case .Month:
                if (dateComp.day != 1){//不是1号
                    let monthComponent = DateComponents(day:1)
                    adjustDate = calendar.nextDate(after: date, matching: monthComponent, matchingPolicy: .nextTime, repeatedTimePolicy: Calendar.RepeatedTimePolicy.first, direction: Calendar.SearchDirection.backward)!;
                }
            case .Week:
                if (dateComp.weekday != calendar.firstWeekday){//不是本周
                    let weekDayComponent = DateComponents(weekday:calendar.firstWeekday)
                    adjustDate = calendar.nextDate(after: date, matching: weekDayComponent, matchingPolicy: .nextTime, repeatedTimePolicy: Calendar.RepeatedTimePolicy.first, direction: Calendar.SearchDirection.backward)!;
                }
            default:
                break;
            }
            
            self.beginDate = adjustDate;
            self.datePicker!.date = adjustDate;
            self.resetButtonError(self.beginButton!);
            self.beginButton!.setTitle("从\(self.beginDate.defaultDateString())", for: .normal);
        }else if (self.endButton != nil && self.endButton!.isSelected){
            switch self.intervalType {
            case .Month:
                if (dateComp.year != todayComp.year || dateComp.month != todayComp.month){//不是本月
                    let monthComponent = DateComponents(day:1)
                    let nextMonth = calendar.nextDate(after: date, matching: monthComponent, matchingPolicy: .nextTime);
                    adjustDate = Date(timeInterval: -1, since: nextMonth!);
                }else{//本月取最后一天
                    adjustDate = Date();
                }
            case .Week:
                if (dateComp.yearForWeekOfYear != todayComp.yearForWeekOfYear || dateComp.weekOfYear != todayComp.weekOfYear){//不是本周
                    let weekDayComponent = DateComponents(weekday:calendar.firstWeekday)
                    let nextWeek = calendar.nextDate(after: date, matching: weekDayComponent, matchingPolicy: .nextTime);
                    adjustDate = Date(timeInterval: -1, since: nextWeek!);
                }else{//本月取最后一天
                    adjustDate = Date();
                }
            case .Day:
                if (calendar.isDateInToday(adjustDate)){
                    adjustDate = Date();
                }else{
                    let dayComponent = DateComponents(hour:0);
                    let nextDay = calendar.nextDate(after: date, matching: dayComponent, matchingPolicy: .nextTime);
                    adjustDate = Date(timeInterval: -1, since: nextDay!);
                }
            }
            print("pickerdate-end:\(dateFormatter.string(from: adjustDate))")
            self.endDate = adjustDate;
            self.datePicker!.date = adjustDate;
            self.endButton!.setTitle("至\(self.endDate.defaultDateString())", for: .normal);
            self.resetButtonError(self.endButton!);
        }
    }
    
    func customDateBeginButton(_ superFrame:CGRect) -> UIButton{
        let frame = CGRect(x:100,y:0,width:80,height:superFrame.height);
        let button = self.customDateButton(frame, title:"开始日期");
        button.addTarget(self, action: #selector(beginDateButtonClicked(_:)), for: .touchUpInside);
        return button;
    }
    func customDateEndButton(_ superFrame:CGRect) -> UIButton{
        let frame = CGRect(x:180,y:0,width:80,height:superFrame.height);
        let button = self.customDateButton(frame, title:"结束日期");
        button.addTarget(self, action: #selector(endDateButtonClicked(_:)), for: .touchUpInside);
        return button;
    }
    
    init() {
        self.beginDate = Calendar.current.startOfDay(for: Date());
    }
    var beginIsSelected:Bool = true;
    var beginDate:Date;
    @objc func beginDateButtonClicked(_ sender:UIButton) -> Void{
        self.datePicker?.maximumDate = self.endDate;
        self.datePicker?.minimumDate = DDateManager.sharedManager().initialDate();
        self.beginButton!.isSelected = true;
        self.endButton!.isSelected = false;
        self.datePicker?.date = self.beginDate;
    }
    var endDate:Date = Date();
    @objc func endDateButtonClicked(_ sender:UIButton) -> Void{
        self.datePicker?.minimumDate = self.beginDate;
        self.datePicker?.maximumDate = Date();
        self.endButton!.isSelected = true;
        self.beginButton!.isSelected = false;
        self.datePicker?.date = self.endDate;
    }
    
    func customDateButton(_ frame:CGRect, title:String) -> UIButton{
        let button:UIButton = UIButton(frame: frame);
        button.autoresizingMask = [.flexibleHeight];
        button.setTitleColor(UIColor.gray, for: .normal);
        button.setTitleColor(UIColor.h_blue(), for: .selected);
        button.setTitle(title, for: .normal);
        button.titleLabel?.adjustsFontSizeToFitWidth = true;
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .light);
        return button;
    }
    func resetButtonError(_ button:UIButton?) -> Void{
        button?.setTitleColor(UIColor.gray, for: .normal);
        button?.setTitleColor(UIColor.h_blue(), for: .selected);
    }
    
    func customDateDoneButton(_ superFrame:CGRect) -> UIButton{
        let frame:CGRect = CGRect(x:superFrame.width - 50,y:0,width:50,height:superFrame.size.height);
        let button:UIButton = UIButton(frame: frame);
        button.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin];
        button.backgroundColor = UIColor.red;
        button.setTitleColor(UIColor.white, for: .normal);
        button.setTitle("确定", for: .normal);
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .light);
        button.addTarget(self, action: #selector(customDateDoneButtonClicked(_:)), for: .touchUpInside);
        return button;
    }
    
    func setButtonError(_ button:UIButton?) -> Void{
        button?.setTitleColor(UIColor.red, for: .normal);
        button?.setTitleColor(UIColor.red, for: .selected);
    }
    
    var doneClosure:((Date, Date) -> Void)?;
    @objc func customDateDoneButtonClicked(_ sender:UIButton) -> Void{
//        if (self.beginDate == nil){
//            self.setButtonError(self.beginButton);
//            self.beginButton?.isSelected = true;
//            self.endButton?.isSelected = false;
//            _ = self.beginButton?.shakeOnHorizontal();
//            return;
//        }
//        if (self.endDate == nil){
//            self.setButtonError(self.endButton);
//            self.beginButton?.isSelected = false;
//            self.endButton?.isSelected = true;
//            _ = self.endButton?.shakeOnHorizontal();
//            return;
//        }
        self.isEditing = false;
        if (self.doneClosure != nil){
            self.doneClosure!(self.beginDate, self.endDate);
        }
    }
}
